// zmienna globalna mapy
var map;
var lat = [];
var lng = [];
var title = [];
var icon = [];
var markers_count = 0;
var size = new google.maps.Size(32, 32);
var startPoint = new google.maps.Point(0, 0);
var anchorPoint = new google.maps.Point(16, 16);
var main_points = [1, 4, 5, 6, 8, 9, 10, 20, 31, 36, 43, 48, 51, 52];

// ścieżki do ikon i ich cieni
var rain = "images/weather/weather_icon_04.png";
var fullSun = "images/weather/weather_icon_12.png";
var cloudSun = "images/weather/weather_icon_07.png";
var snow = "images/weather/weather_icon_10.png";
var tempest = "images/weather/weather_icon_02.png";

// zoomowanie na wybrany polygon poprzez listener na mapie
function zoomPolygon(polygon, points) {
	google.maps.event.addListener(polygon, 'click', function(zdarzenie) {
		zoomPoly(points);
	});
}

// zoomowanie na wybrany polygon wybierany z panelu
function zoomPoly(points) {
	var bounds = new google.maps.LatLngBounds();
	for(var i = 0; i < points.length; i++) {
		bounds.extend(points[i]);
	}
	map.fitBounds(bounds);
}

// pokazanie polygonu
function showPolygon(polygon, points) {
	polygon.setMap(map);
	zoomPolygon(polygon, points);
}

function removeAllPolygons() {
	mazury_p.setMap(null);
	olsztyn_p.setMap(null);
	zatoka_gdanska_p.setMap(null);
	pomorze_polnoc_p.setMap(null);
	zalew_wislany_p.setMap(null);
	jezioro_solinskie_p.setMap(null);
	jez_paczkowskie_otmuchowskie_nyskie_p.setMap(null);
	jezioro_czorsztynskie_p.setMap(null);
	jez_jeziorsko_sulejowskie_p.setMap(null);
	poj_drawskie_p.setMap(null);
	rospuda_hancza_august_p.setMap(null);
}

// tworzenie polygonu z punktów
function createPolygon(points, color, opacity) {
	return new google.maps.Polygon({
		paths : points,
		strokeColor : "#400000",
		strokeOpacity : 0.15,
		strokeWeight : 1,
		fillColor : color,
		fillOpacity : opacity
	});
}

// tworzenie marker managera do zarządzania markerami względem zooma
function setupMarkers() {
	mgr = new MarkerManager(map);

	google.maps.event.addListener(mgr, 'loaded', function() {
		mgr.addMarkers(createMarkers(1, 1), 0, 4);
		mgr.addMarkers(createMarkers(14, 1), 5, 7);
		mgr.addMarkers(createMarkers(-1, 0), 8);
		mgr.refresh();
	});
}

/* *
 * tworzenie markerów z tablic z danymi, dodawanie do każdego markera
 * listenera w celu wyświetlania danych ajaxowych w panelu
 *
 * mode=0 -> dla wszystkich markerów
 * mode=1 -> dla wybranych miejscówek (mały zoom)
 */
function createMarkers(n, mode) {
	var batch = [];

	var locations_data = [];

	$.ajax({
		type : 'POST',
		async : false,
		dataType : 'json',
		url : 'index.php?r=data/getMarkersWeatherData',
		data : {
			'timestamp' : getDBCurrentDate(),
			mode : mode
		},
		success : function(data, textStatus, jqXHR) {
			for( i = 0; i < data.length; i++) {
				if (data=='brak')
					locations_data=data;
				else
					locations_data[i] = data[i];
			}
		},
		error : function(data, textStatus, jqXHR) {
			var thisline = new Error().lineNumber;
			alert('157map.js:' + thisline);
		},
		dataType : 'json'
	});

	if (locations_data!='brak') {
		if(n == -1)
			n = locations_data.length;
	
		for(var i = 0; i < n; i++) {
			weather_summary_icon = fullSun;
			if(locations_data[i]['weather_conditions']['total_col_snow'] > 1) {
				weather_summary_icon = snow;
			} else if(locations_data[i]['weather_conditions']['total_col_rain'] > 1) {
				weather_summary_icon = rain;
			} else if((locations_data[i]['weather_conditions']['low_cloud_fra'] + locations_data[i]['weather_conditions']['mid_cloud_fra']) / 2 > 30) {
				weather_summary_icon = cloudSun;
			}
			temp = Math.round((locations_data[i]['weather_conditions']['skin_temp'] - 273.15) * 100) / 100;
			//Math.round(skin_temp * 100) / 100
			label = locations_data[i]['location_title'] + '<br />' + temp + '&deg;C';
	
			var marker = new MarkerWithLabel({
				position : new google.maps.LatLng(locations_data[i]['location_latitude'], locations_data[i]['location_longitude']),
				icon : new google.maps.MarkerImage(weather_summary_icon, size, startPoint, anchorPoint),
				title : locations_data[i]['location_title'],
				labelContent : label,
				labelAnchor : new google.maps.Point(16, -11),
				labelClass : "labels", // the CSS class for the label
				labelStyle : {
					opacity : 0.75
				},
				labelVisible : false
			});
	
			google.maps.event.addListener(marker, 'click', function() {
				$.ajax({
					type : 'POST',
					dataType : 'json',
					url : 'index.php?r=data/getMarkerData',
					data : {
						location : this.title,
						'timestamp' : getDBCurrentDate()
					},
					success : function(data, textStatus, jqXHR) {
						changeInfo(data);
						calcChartsData(data[0]);
						createCookie('title', data[1], 7);
					},
					error : function(data, textStatus, jqXHR) {
						var thisline = new Error().lineNumber;
						alert('201map.js:' + thisline);
					},
					dataType : 'json'
				});
			});
			google.maps.event.addListener(marker, 'mouseover', function() {
				str = this.title;
				tmp = str.replace(' ', '').replace(' ', '').replace(' ', '').replace('.', '_');
				$('#markerDiv_' + tmp).fadeIn('fast');
			});
			google.maps.event.addListener(marker, 'mouseout', function() {
				str = this.title;
				tmp = str.replace(' ', '').replace(' ', '').replace(' ', '').replace('.', '_');
				$('#markerDiv_' + tmp).fadeOut('fast');
			});
			batch.push(marker);
		}
		return batch;
	}
}

function changeInfo(data) {
	radians_to_degress = 57.2957795;
	kelvins_to_celsius_interval = 273.15;
	wind_speed = Math.sqrt(data['u_wind'] * data['u_wind'] + data['v_wind'] * data['v_wind']);
	skin_temp = data['skin_temp'] - kelvins_to_celsius_interval;
	wind_direction = Math.abs(Math.atan(data['v_wind'] / data['u_wind']) * radians_to_degress);
	weather_summary_icon = fullSun;

	if(data['total_col_snow'] > 1) {
		weather_summary_icon = snow;
	} else if(data['total_col_rain'] > 1) {
		weather_summary_icon = rain;
	} else if((data['low_cloud_fra'] + data['mid_cloud_fra']) / 2 > 25) {
		weather_summary_icon = cloudSun;
	}

	if(data['v_wind'] > 0) {
		if(data['u_wind'] > 0) {

		} else {
			wind_direction += 270;
		}
	} else {
		if(data['u_wind'] > 0) {
			wind_direction += 90;
		} else {
			wind_direction += 180;
		}
	}

	document.getElementById('weather_summary_icon').innerHTML = '<img src="' + weather_summary_icon + '"/>';
	document.getElementById('title').innerHTML = data[1];
	document.getElementById('longitude').innerHTML = data[2] + '&deg; N';
	document.getElementById('latitude').innerHTML = data[3] + '&deg; E';
	document.getElementById('wind_speed').innerHTML = Math.round(wind_speed * 100) / 100 + ' m\/s';
	document.getElementById('skin_temp').innerHTML = Math.round(skin_temp * 100) / 100 + '&deg; C';

	$('#arrow_wind_speed').css('transform', 'rotate(' + wind_direction + 'deg)');
	$('#arrow_wind_speed').css('-ms-transform', 'rotate(' + wind_direction + 'deg)');
	/* IE 9 */
	$('#arrow_wind_speed').css('-moz-transform', 'rotate(' + wind_direction + 'deg)');
	/* Firefox */
	$('#arrow_wind_speed').css('-webkit-transform', 'rotate(' + wind_direction + 'deg)');
	/* Safari and Chrome */
	$('#arrow_wind_speed').css('-o-transform', 'rotate(' + wind_direction + 'deg)');
	/* Opera */
	// document.getElementById('addFav').setAttribute('onclick','addFavourite('+data[0]+',\''+data[1]+'\');');
	checkFavourite(data[0], data[1]);
}

function loadRegions() {
	$.ajax({
		type : 'POST',
		dataType : 'json',
		url : 'index.php?r=data/getRegions',
		success : function(data) {
			for( i = 0; i < data.length; i++) {
				var newElement = document.createElement('span');
				newElement.textContent = data[i]['name'];
				newElement.id = "region_" + data[i]['id'];
				newElement.setAttribute('onmouseover', 'removeAllPolygons();showAllPolygons(0.15, 0.80, \'' + data[i]['code'] + '\');');
				newElement.setAttribute('onmouseout', 'removeAllPolygons();showAllPolygons(0.15);');
				var newElement2 = document.createElement('img');
				newElement2.setAttribute('src', 'images/plus.png');
				newElement2.setAttribute('class', 'toggle');
				newElement2.id = "r_" + data[i]['id'];
				newElement2.setAttribute('onclick', 'loadLocations(' + data[i]['id'] + ');');
				document.getElementById('regions').appendChild(newElement2);
				document.getElementById('regions').appendChild(newElement);
				document.getElementById('regions').appendChild(document.createElement('br'));
			}
		},
		error : function(data, textStatus, jqXHR) {
			var thisline = new Error().lineNumber;
			alert('285map.js:' + thisline);
		}
	});
}

function removeRegionChilds(number) {
	var cell = document.getElementById('region_' + number);
	if(cell.hasChildNodes())
		while(cell.childNodes.length >= 2) {
			cell.removeChild(cell.lastChild);
		}
	document.getElementById('r_' + number).onclick = function() {
		loadLocations(number);
	};
	document.getElementById('r_' + number).setAttribute('src', 'images/plus.png');
}

function loadLocations(id) {
	$.ajax({
		type : 'POST',
		dataType : 'json',
		data : {
			id_reg : id
		},
		url : 'index.php?r=data/getLocations',
		success : function(data) {
			document.getElementById('r_' + id).setAttribute('src', 'images/minus.png');
			region = 'region_' + id;
			var newElement = document.createElement('div');
			newElement.id = 'div_' + region;
			newElement.style = 'display: none';
			document.getElementById(region).appendChild(newElement);
			for( i = 0; i < data.length; i++) {
				var newElement = document.createElement('span');
				newElement.textContent = data[i]['title'];
				newElement.id = 'location_' + data[i]['id'];
				newElement.className = 'location_view';
				var newElement2 = document.createElement('img');
				newElement2.setAttribute('src', 'images/zoom.png');
				newElement2.setAttribute('alt', '');
				newElement2.setAttribute('onclick', 'fitBounds(' + data[i]['latitude'] + ',' + data[i]['longitude'] + ');changePanelInfo(\'' + data[i]['title'] + '\');');
				newElement2.className = 'zoom';
				document.getElementById('div_' + region).appendChild(newElement);
				document.getElementById('div_' + region).appendChild(newElement2);
				document.getElementById('div_' + region).appendChild(document.createElement('br'));
				$('#div_' + region).slideDown('slow');
			}
			document.getElementById('r_' + id).onclick = function() {
				$('#div_region_' + id).slideUp('slow', function() {
					removeRegionChilds(id);
				});
			};
		},
		error : function(data, textStatus, jqXHR) {
			var thisline = new Error().lineNumber;
			alert('341map.js:' + thisline);
		},
		dataType : 'json'
	});
}

function fitBounds(lat, lng) {
	var latlngbounds = new google.maps.LatLngBounds();
	latlngbounds.extend(new google.maps.LatLng(lat, lng));
	map.setCenter(latlngbounds.getCenter());
	map.setZoom(12);
}

function changePanelInfo(title) {

	$.ajax({
		type : 'POST',
		dataType : 'json',
		url : 'index.php?r=data/getMarkerData',
		data : {
			location : title,
			'timestamp' : getDBCurrentDate()
		},
		success : function(data, textStatus, jqXHR) {
			if (data!='brak') {
				changeInfo(data);
				calcChartsData(data[0]);
				createCookie('title', data[1], 7);
			}
		},
		error : function(data, textStatus, jqXHR) {
			var thisline = new Error().lineNumber;
			alert('364map.js:' + thisline);
		},
		dataType : 'json'
	});
}

function getDBCurrentDate() {
	var now = new Date();

	now.setMinutes(0);
	now.setSeconds(0);
	month = 0;
	day = 0;
	hours = 0;
	minutes = 0;
	seconds = 0;

	if(now.getMonth() + 1 < 10)
		month = '0' + now.getMonth() + 1
	else
		month = now.getMonth() + 1;

	if(now.getDate() < 10)
		day = '0' + now.getDate()
	else
		day = now.getDate();

	if(now.getHours() < 10)
		hours = '0' + now.getHours()
	else
		hours = now.getHours();

	if(now.getMinutes() < 10)
		minutes = '0' + now.getMinutes()
	else
		minutes = now.getMinutes();

	if(now.getSeconds() < 10)
		seconds = '0' + now.getSeconds()
	else
		seconds = now.getSeconds();
	dateString = now.getFullYear() + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;

	return dateString;
}

function showAllPolygons(opacity_rest, opacity_main, main_name) {
	if(arguments.length == 1) {
		mazury_p = createPolygon(mazury, "#73FFFF", opacity_rest);
		olsztyn_p = createPolygon(olsztyn, "#73FFFF", opacity_rest);
		zatoka_gdanska_p = createPolygon(zatoka_gdanska, "#73FFFF", opacity_rest);
		pomorze_polnoc_p = createPolygon(pomorze_polnoc, "#73FFFF", opacity_rest);
		zalew_wislany_p = createPolygon(zalew_wislany, "#73FFFF", opacity_rest);
		jezioro_solinskie_p = createPolygon(jezioro_solinskie, "#73FFFF", opacity_rest);
		jez_paczkowskie_otmuchowskie_nyskie_p = createPolygon(jez_paczkowskie_otmuchowskie_nyskie, "#73FFFF", opacity_rest);
		jezioro_czorsztynskie_p = createPolygon(jezioro_czorsztynskie, "#73FFFF", opacity_rest);
		jez_jeziorsko_sulejowskie_p = createPolygon(jez_jeziorsko_sulejowskie, "#73FFFF", opacity_rest);
		poj_drawskie_p = createPolygon(poj_drawskie, "#73FFFF", opacity_rest);
		rospuda_hancza_august_p = createPolygon(rospuda_hancza_august, "#73FFFF", opacity_rest);
	} else if(arguments.length == 3) {
		if(main_name == 'mazury')
			mazury_p = createPolygon(mazury, "#73FFFF", opacity_main);
		else
			mazury_p = createPolygon(mazury, "#73FFFF", opacity_rest);
		if(main_name == 'olsztyn')
			olsztyn_p = createPolygon(olsztyn, "#73FFFF", opacity_main);
		else
			olsztyn_p = createPolygon(olsztyn, "#73FFFF", opacity_rest);
		if(main_name == 'zatoka_gdanska')
			zatoka_gdanska_p = createPolygon(zatoka_gdanska, "#73FFFF", opacity_main);
		else
			zatoka_gdanska_p = createPolygon(zatoka_gdanska, "#73FFFF", opacity_rest);
		if(main_name == 'pomorze_polnoc')
			pomorze_polnoc_p = createPolygon(pomorze_polnoc, "#73FFFF", opacity_main);
		else
			pomorze_polnoc_p = createPolygon(pomorze_polnoc, "#73FFFF", opacity_rest);
		if(main_name == 'zalew_wislany')
			zalew_wislany_p = createPolygon(zalew_wislany, "#73FFFF", opacity_main);
		else
			zalew_wislany_p = createPolygon(zalew_wislany, "#73FFFF", opacity_rest);
		if(main_name == 'jezioro_solinskie')
			jezioro_solinskie_p = createPolygon(jezioro_solinskie, "#73FFFF", opacity_main);
		else
			jezioro_solinskie_p = createPolygon(jezioro_solinskie, "#73FFFF", opacity_rest);
		if(main_name == 'jez_paczkowskie_otmuchowskie_nyskie')
			jez_paczkowskie_otmuchowskie_nyskie_p = createPolygon(jez_paczkowskie_otmuchowskie_nyskie, "#73FFFF", opacity_main);
		else
			jez_paczkowskie_otmuchowskie_nyskie_p = createPolygon(jez_paczkowskie_otmuchowskie_nyskie, "#73FFFF", opacity_rest);
		if(main_name == 'jezioro_czorsztynskie')
			jezioro_czorsztynskie_p = createPolygon(jezioro_czorsztynskie, "#73FFFF", opacity_main);
		else
			jezioro_czorsztynskie_p = createPolygon(jezioro_czorsztynskie, "#73FFFF", opacity_rest);
		if(main_name == 'jez_jeziorsko_sulejowskie')
			jez_jeziorsko_sulejowskie_p = createPolygon(jez_jeziorsko_sulejowskie, "#73FFFF", opacity_main);
		else
			jez_jeziorsko_sulejowskie_p = createPolygon(jez_jeziorsko_sulejowskie, "#73FFFF", opacity_rest);
		if(main_name == 'poj_drawskie')
			poj_drawskie_p = createPolygon(poj_drawskie, "#73FFFF", opacity_main);
		else
			poj_drawskie_p = createPolygon(poj_drawskie, "#73FFFF", opacity_rest);
		if(main_name == 'rospuda_hancza_august')
			rospuda_hancza_august_p = createPolygon(rospuda_hancza_august, "#73FFFF", opacity_main);
		else
			rospuda_hancza_august_p = createPolygon(rospuda_hancza_august, "#73FFFF", opacity_rest);
	}

	showPolygon(mazury_p, mazury);
	showPolygon(olsztyn_p, olsztyn);
	showPolygon(zatoka_gdanska_p, zatoka_gdanska);
	showPolygon(pomorze_polnoc_p, pomorze_polnoc);
	showPolygon(zalew_wislany_p, zalew_wislany);
	showPolygon(jezioro_solinskie_p, jezioro_solinskie);
	showPolygon(jez_paczkowskie_otmuchowskie_nyskie_p, jez_paczkowskie_otmuchowskie_nyskie);
	showPolygon(jezioro_czorsztynskie_p, jezioro_czorsztynskie);
	showPolygon(jez_jeziorsko_sulejowskie_p, jez_jeziorsko_sulejowskie);
	showPolygon(poj_drawskie_p, poj_drawskie);
	showPolygon(rospuda_hancza_august_p, rospuda_hancza_august);
}

// inicjalizacja mapy
function mapStart() {
	loadRegions();
	cookie = decodeURIComponent(readCookie('title'));
	if(cookie == null || cookie == 'null')
		changePanelInfo('Gdańsk');
	else if(cookie != null || cookie != '')
		changePanelInfo(cookie);
	var coords = new google.maps.LatLng(51.917168, 19.138184);
	var mapOptions = {
		zoom : 6,
		center : coords,
		mapTypeId : google.maps.MapTypeId.TERRAIN,
		mapTypeControl : true,
		scaleControl : true,
		streetViewControl : false
	};
	map = new google.maps.Map(document.getElementById("mapka"), mapOptions);

	// listener na zmianę zooma w celu przerysowania markerów
	var listener = google.maps.event.addListener(map, 'bounds_changed', function() {
		setupMarkers();
		google.maps.event.removeListener(listener);
	});
	// tworzenie poszczególnych polygonów + pokazywanie ich na mapie
	showAllPolygons(0.15);
	getFavourites();
}